
import { globalUtils } from '../../common/js/global-utils/global-utils-all';
import { uiUtils } from '../../common/js/ui-utils/ui-utils-all';
import jQuery from 'jquery';
import Pure from 'pure-frontend';

/* SOURCE-CODE-START */

"use strict";

/**
 * @class
 * @param {*} tabs 
 * @param {*} fields 
 * @param {*} labels 
 */
function TableSelectionTabs(tabs, fields, labels) {
  tabs = globalUtils.emptyObjectIfNullOrUndefined(tabs);
  fields = globalUtils.emptyArrayIfNullOrUndefined(fields);
  labels = globalUtils.emptyObjectIfNullOrUndefined(labels);

  var nav1 = tabs.nav1;
  var tabPane1 = tabs.tabPane1;
  var table1 = tabs.table1;
  var table1MoveUpDown = tabs.table1MoveUpDown;
  var nav2 = tabs.nav2;
  var tabPane2 = tabs.tabPane2;
  var table2 = tabs.table2;

  this._jqNav1 = (nav1 instanceof jQuery)
    ? nav1 : jQuery(nav1);
  this._jqTabPane1 = (tabPane1 instanceof jQuery)
    ? tabPane1 : jQuery(tabPane1);
  this._jqTable1 = (table1 instanceof jQuery)
    ? table1 : jQuery(table1);
  this._table1Url = tabs.table1Url;

  this._jqNav2 = (nav2 instanceof jQuery)
    ? nav2 : jQuery(nav2);
  this._jqTabPane2 = (tabPane2 instanceof jQuery)
    ? tabPane2 : jQuery(tabPane2);
  this._jqTable2 = (table2 instanceof jQuery)
    ? table2 : jQuery(table2);
  this._table2Url = tabs.table2Url;

  this._tableFields = fields;
  this._confirmLabel = labels.confirmLabel;
  this._cancelLabel = labels.cancelLabel;
  this._initialFlag = true;
  this._refreshFlag = true;
  this._table1MoveUpDown = table1MoveUpDown;

  var tabPane1Id = 'tab_' + TableSelectionTabs.sequenceGenerator.nextValue();
  this._jqNav1.attr('data-target', '#' + tabPane1Id);
  this._jqTabPane1.attr('id', tabPane1Id);
  var tabPane2Id = 'tab_' + TableSelectionTabs.sequenceGenerator.nextValue();
  this._jqNav2.attr('data-target', '#' + tabPane2Id);
  this._jqTabPane2.attr('id', tabPane2Id);
}

TableSelectionTabs.sequenceGenerator = new Pure.fn.SequenceGenerator(100001);

/**
 * @description 初始或者重置
 * @param {*} customQuery 
 */
TableSelectionTabs.prototype.initOrResetTabs = function (customQuery) {
  customQuery = globalUtils.emptyObjectIfNullOrUndefined(customQuery);
  var tabs = this;

  if (tabs._initialFlag) {
    // 初始tab页
    //

    // 切换到 tab2 标签页后刷新 table2 数据
    tabs._jqNav2.on('show.bs.tab', function () {
      if (tabs._refreshFlag) {
        uiUtils.dataGrid.refresh(tabs._jqTable2);
        tabs._refreshFlag = false;
      }
    });

    // table1 加载数据成功后启用 tab2 标签页
    tabs._jqTable1.on('load-success.bs.table', function () {
      tabs._jqNav2.removeAttr('disabled');
      // 标记 table2 需要刷新
      tabs._refreshFlag = true;
    });

    // 初始 table1
    tabs.doInitTable1(customQuery);
    // 初始 table2
    tabs.doInitTable2(customQuery);

    tabs._initialFlag = false;
  } else {
    // 重置tab页
    //

    // 默认显示 tab1 标签页
    tabs._jqNav1.tab('show');

    // 重新查询 table1 数据 
    uiUtils.dataGrid.newQuery(tabs._jqTable1, {
      customQuery: customQuery
    });

    // 重新查询 table2 数据
    uiUtils.dataGrid.newQuery(tabs._jqTable2);
  }
};

/**
 * @description 初始 table1
 * @param {*} customQuery 
 */
TableSelectionTabs.prototype.doInitTable1 = function (customQuery) {
  var tabs = this;

  uiUtils.dataGrid.init(tabs._jqTable1, {
    url: tabs._table1Url,
    sidePagination: 'client',
    customQuery: customQuery,
    columns: tabs._tableFields.concat([{
      // 操作列
      field: 'operate',
      formatter: TableSelectionTabs.formatTable1OperationColumn.bind(tabs, tabs),
      events: {
        'click .cancel': TableSelectionTabs.handleTable1CancelOperation.bind(tabs, tabs),
        'click .moveUp': TableSelectionTabs.handleTable1MoveUpOperation.bind(tabs, tabs),
        'click .moveDown': TableSelectionTabs.handleTable1MoveDownOperation.bind(tabs, tabs)
      }
    }])
  });
};

/**
 * @description 初始 table2
 * @param {*} customQuery 
 */
TableSelectionTabs.prototype.doInitTable2 = function (customQuery) {
  var tabs = this;

  uiUtils.dataGrid.init(tabs._jqTable2, {
    url: tabs._table2Url,
    checkboxHeader: false,
    columns: [{
      // 复选框列
      formatter: TableSelectionTabs.formatTable2CheckColumn.bind(tabs, tabs)
    }].concat(tabs._tableFields, [{
      // 操作列
      field: 'operate',
      formatter: TableSelectionTabs.formatTable2OperationColumn.bind(tabs, tabs),
      events: {
        'click .confirm': TableSelectionTabs.handleTable2ConfirmOperation.bind(tabs, tabs),
        'click .cancel': TableSelectionTabs.handleTable2CancelOperation.bind(tabs, tabs)
      }
    }])
  });
};

/**
 * @description 格式化 table1 的操作列
 * @param {*} tabs 
 * @param {*} value 
 * @param {*} row 
 * @param {*} index 
 * @returns 
 */
TableSelectionTabs.formatTable1OperationColumn = function (tabs, value, row, index) {
  var moveUpDown = (tabs._table1MoveUpDown === true);

  if (moveUpDown) {
    var data = tabs._jqTable1.bootstrapTable('getData');
    var moveUpDisabled = (index <= 0)
      ? ' disabled' : '';
    var moveDownDisabled = (index + 1 >= data.length)
      ? ' disabled' : '';

    return [
      '<a class="moveUp" href="javascript:void(0)"' + moveUpDisabled + '>',
      '<span>${t("ui.system.common.operation.moveUp")}</span>',
      '</a>',
      '&nbsp;',
      '<a class="moveDown" href="javascript:void(0)"' + moveDownDisabled + '>',
      '<span>${t("ui.system.common.operation.moveDown")}</span>',
      '</a>',
      '&nbsp;',
      '<a class="cancel" href="javascript:void(0)">',
      '<span>', tabs._cancelLabel, '</span>',
      '</a>'
    ].join('\n');
  } else {
    return [
      '<a class="cancel" href="javascript:void(0)">',
      '<span>', tabs._cancelLabel, '</span>',
      '</a>'
    ].join('\n');
  }
};

/**
 * @description 格式化 table2 的复选框列
 * @param {*} tabs 
 * @param {*} value 
 * @param {*} row 
 * @param {*} index 
 * @returns 
 */
TableSelectionTabs.formatTable2CheckColumn = function (tabs, value, row, index) {
  var data = tabs._jqTable1.bootstrapTable('getData');
  var ids = data.map(function (record) {
    return record.id;
  });

  var selectedFlag = ids.includes(row.id);
  return {
    disabled: true,
    checked: selectedFlag
  }
};

/**
 * @description 格式化 table2 的操作列
 * @param {*} tabs 
 * @param {*} value 
 * @param {*} row 
 * @param {*} index 
 * @returns 
 */
TableSelectionTabs.formatTable2OperationColumn = function (tabs, value, row, index) {
  var data = tabs._jqTable1.bootstrapTable('getData');
  var ids = data.map(function (record) {
    return record.id;
  });

  var selectedFlag = ids.includes(row.id);
  if (selectedFlag) {
    return [
      '<a class="confirm" href="javascript:void(0)" disabled>',
      '<span>', tabs._confirmLabel, '</span>',
      '</a>',
      '&nbsp;',
      '<a class="cancel" href="javascript:void(0)">',
      '<span>', tabs._cancelLabel, '</span>',
      '</a>'
    ].join('\n');
  } else {
    return [
      '<a class="confirm" href="javascript:void(0)">',
      '<span>', tabs._confirmLabel, '</span>',
      '</a>',
      '&nbsp;',
      '<a class="cancel" href="javascript:void(0)" disabled>',
      '<span>', tabs._cancelLabel, '</span>',
      '</a>'
    ].join('\n');
  }
};

/**
 * @description 处理 table1 的上移操作
 * @param {*} tabs 
 * @param {*} e 
 * @param {*} value 
 * @param {*} row 
 * @param {*} index 
 */
TableSelectionTabs.handleTable1MoveUpOperation = function (tabs, e, value, row, index) {
  if (index <= 0) {
    return;
  }

  var data = tabs._jqTable1.bootstrapTable('getData');
  var prevRowData = data[index - 1];
  var currRowData = data[index];

  tabs._jqTable1.bootstrapTable('updateRow', {
    index: index - 1,
    row: currRowData,
    replace: true
  });

  tabs._jqTable1.bootstrapTable('updateRow', {
    index: index,
    row: prevRowData,
    replace: true
  });
};

/**
 * @description 处理 table1 的下移操作
 * @param {*} tabs 
 * @param {*} e 
 * @param {*} value 
 * @param {*} row 
 * @param {*} index 
 */
TableSelectionTabs.handleTable1MoveDownOperation = function (tabs, e, value, row, index) {
  var data = tabs._jqTable1.bootstrapTable('getData');

  if (index + 1 >= data.length) {
    return;
  }

  var currRowData = data[index];
  var nextRowData = data[index + 1];

  tabs._jqTable1.bootstrapTable('updateRow', {
    index: index,
    row: nextRowData,
    replace: true
  });

  tabs._jqTable1.bootstrapTable('updateRow', {
    index: index + 1,
    row: currRowData,
    replace: true
  });
};

/**
 * @description 处理 table1 的取消操作
 * @param {*} tabs 
 * @param {*} e 
 * @param {*} value 
 * @param {*} row 
 * @param {*} index 
 */
TableSelectionTabs.handleTable1CancelOperation = function (tabs, e, value, row, index) {
  // table1 删除指定记录
  tabs._jqTable1.bootstrapTable('remove', {
    field: 'id',
    values: [row.id]
  });

  // 标记 table2 需要刷新
  tabs._refreshFlag = true;
};

/**
 * @description 处理 table2 的确定操作
 * @param {*} tabs 
 * @param {*} e 
 * @param {*} value 
 * @param {*} row 
 * @param {*} index 
 */
TableSelectionTabs.handleTable2ConfirmOperation = function (tabs, e, value, row, index) {
  // 避免离开页面时表单数据比较结果与预期不符合
  var newRow = _.cloneDeep(row);
  delete newRow[0];

  // table1 新增记录
  tabs._jqTable1.bootstrapTable('append', newRow);

  // table2 更新复选框列和操作列
  tabs._jqTable2.bootstrapTable('check', index);
  tabs._jqTable2.bootstrapTable('updateCell', {
    index: index,
    field: 'operate',
    value: null,
    reinit: false,
  });
};

/**
 * @description 处理 table2 的取消操作
 * @param {*} tabs 
 * @param {*} e 
 * @param {*} value 
 * @param {*} row 
 * @param {*} index 
 */
TableSelectionTabs.handleTable2CancelOperation = function (tabs, e, value, row, index) {
  // table1 删除指定记录
  tabs._jqTable1.bootstrapTable('remove', {
    field: 'id',
    values: [row.id]
  });

  // table2 更新复选框列和操作列
  tabs._jqTable2.bootstrapTable('uncheck', index);
  tabs._jqTable2.bootstrapTable('updateCell', {
    index: index,
    field: 'operate',
    value: null,
    reinit: false,
  });
};


/* SOURCE-CODE-END */

export { TableSelectionTabs };
